/**
 * Malsha Sewwandi 2014-06-27
 */

ReceiptRequest = new Object();

var receipt_fund_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'name', 'code', 'unitValue' ]
});

var receipt = Ext.create('Ext.data.Store', {
	fields : [ 'customer_code', 'customer_name', 'credit_balance', 'payment_type', 'amount', 'fund' ]
});

var receipt_req_store = Ext.create('Ext.data.Store', {
	fields : [ 'customerId', 'customerCode', 'customerName', 'creditBalnce', 'paymentType', 'customerType' ]

});
ReceiptRequest.getReceiptGrid = function() {
	var receiptgrid = null;
	receiptgrid = Ext.create('Ext.grid.Panel', {
		title : 'Receipt',
		id : 'receipt_grid',
		store : receipt_req_store,
		height : 380,
		plugins : [ Ext.create('Ext.grid.plugin.CellEditing', {
			clicksToEdit : 1
		}) ],
		features : [ {
			ftype : 'summary'
		} ],
		columns : [ {
			header : 'Customer Code',
			dataIndex : 'customerCode',
			width : 85
		}, {
			header : 'Customer Name',
			dataIndex : 'customerName',
			flex : 1
		}, {
			header : 'Credit Balance',
			dataIndex : 'creditBalnce',
			width : 125,
			xtype : 'numbercolumn',
			format : '0,000.0000',
			align : 'right',
		}, {
			header : 'Payment Type',
			dataIndex : 'paymentType',
			width : 85,
			align : 'center',
			editor : {
				xtype : 'combo',
				displayField : 'name',
				valueField : 'type',
				store : Ext.create('Ext.data.Store', {
					fields : [ 'name', 'type' ],
					data : [ {
						name : 'RTGS',
						type : 'R'
					}, {
						name : 'Slip',
						type : 'S'
					}, {
						name : 'Cheque',
						type : 'C'
					}, {
						name : 'Transfer',
						type : 'T'
					} ]
				})
			}
		}, {
			header : 'Amount',
			dataIndex : 'amount',
			width : 125,
			xtype : 'numbercolumn',
			format : '0,000.0000',
			align : 'right',
			summaryType : 'sum',
			summaryRenderer : function(value, summaryData, dataIndex) {
				var val = Ext.util.Format.number(value, '0,000.0000');
				return Ext.String.format('<B>Total</B>\t{0}', val);
			},
			getEditor : function(record) {
				return Ext.create('Ext.grid.CellEditor', {
					field : {
						xtype : 'numberfield',
						hideTrigger : true,
						keyNavEnabled : false,
						msgTarget : 'side',
						mouseWheelEnabled : false,
						maxValue : receiptgrid.getView().getSelectionModel().getSelection()[0].get('creditBalnce')
					}
				});

			}
		} ]
	});

	return receiptgrid;
};

ReceiptRequest.getCeneterPanel = function() {

	return Ext.create('Ext.form.Panel', {
		title : 'Receipt Request',
		bodyPadding : '20',
		autoScroll : true,
		defaults : {
			anchor : '65%'
		},
		frame : true,
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'datefield',
				fieldLabel : 'Date',
				labelWidth : 50,
				width : 225,
				id : 'date',
				value : new Date(),
				format : 'd/m/Y',
				submitFormat : 'd/m/Y',
				padding : '0 15 0 0',
			}, {
				xtype : 'combo',
				fieldLabel : 'Fund<span style="color:red">*</span>',
				flex : 1,
				labelWidth : 90,
				anchor : '70%',
				id : 'fund',
				padding : '0 10 0 0',
				store : receipt_fund_store,
				valueField : 'id',
				displayField : 'code',
				emptyText : 'Select a Fund...',
				isLoaded : false,
				allowBlank : false,
				msgTarget : 'under',
				name : 'fund_id',
				queryMode : 'local',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - {name}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {name}', '</tpl>'),
				listeners : {
					expand : function(combo, opt) {
						if (!combo.isLoaded) {
							Ext.Ajax.request({
								url : 'getFundVsUnitValue.action',
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									combo.getStore().loadRawData(obj.fundDtos);
									combo.isLoaded = true;
								}
							});
						}
					}
				},
				listConfig : {
					listeners : {
						itemclick : function(list, record) {
							Ext.Ajax.request({
								url : 'getReceiptReq.action',
								params : {
									"fund_id" : record.get('id'),
									"affective_date" : Ext.Date.format(Ext.getCmp('date').getValue(), 'd/m/Y'),
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									receipt_req_store.removeAll();
									console.log(obj.paymentRequests);
									receipt_req_store.loadRawData(obj.paymentRequests);
								}
							});
						}
					}
				}
			} ]
		}, ReceiptRequest.getReceiptGrid() ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				dealTypeValue = null;
				dealStore.removeAll();
				this.up('form').getForm().reset();
			}
		}, {
			text : 'Save',
			id : 'save',
			handler : function() {
				var form = this.up('form').getForm();
				var grids = Ext.getCmp('receipt_grid');
				if (form.isValid()) {
					var receiptRequests = [];
					grids.getStore().each(function(record) {
						if (record.get('amount') > 0) {
							var obj = {
								"customerId" : record.get("customerId"),
								"paymentType" : record.get("paymentType"),
								"amount" : record.get("amount"),
								"customerType" : record.get("customerType")
							};
							receiptRequests.push(obj);
						}
					});
					form.url = 'addReceipts.action';
					form.submit({
						params : {
							"receiptRequests" : Ext.encode(receiptRequests),
							"fundId" : Ext.getCmp('fund').getValue()
						},
						success : function(form, action) {
							form.reset();
							Ext.getCmp('save').setText('Save');
							Ext.Msg.alert('Success', 'Saved Successfully');
							Ext.getCmp('receipt_grid').getStore().removeAll();
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', action.result.resulteMsg);
						}
					});
				}
			}
		} ],
		listeners : {
			beforerende : function() {
				App.Core.showLoading('Loading');
			},
			afterrender : function() {
				App.Core.showLoading(false);
			}
		}
	});
};
